package com.example.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

import static java.lang.Character.toUpperCase;

/**
 * TODO
 *
 * @author ding
 * @since 2024/7/4
 */
public class TransUtils {

    /**
     * 翻译工具类
     */
    public static String TransToEn(String ch){
        String url = "https://fanyi-api.baidu.com/api/trans/vip/translate";
        String appid = "20240704002091622";
        String key = "BlXYYB4CFnEIjUi6Fzfc";
        String salt = SaltUtils.getSalt(10);
        String md5 = MD5.md5(appid +ch + salt + key);
        String get = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + ch + "&from=zh&to=en&appid=20240704002091622&salt=" + salt + "&sign=" +md5;
        String res = doGet(get);
        return JSON.parseObject(res).getString("trans_result");
    }

    public static String doGet(String url) {
        //创建一个Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //创建一个get请求
        HttpGet httpGet = new HttpGet(url);
        //响应模型
        CloseableHttpResponse response = null;
        try {
            //由客户端发送get请求
            response = httpClient.execute(httpGet);
            //从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }


    public static String getMethodName(String fieldName) {
        char[] chars = fieldName.toCharArray();
        chars[0] = toUpperCase(chars[0]);
        return String.valueOf(chars);
    }

}
